package com.lyb.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.lyb.spzx.manager.constant.CacheConstant;
import com.lyb.spzx.manager.service.ValidateCodeService;
import com.lyb.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ValidateCodeVo getValidateCode() {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String code = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();
        
        //生成UUID作为验证码的key
        String codekey = UUID.randomUUID().toString().replace("-", "");
        //将验证码存入到redis中
        redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + codekey,code,5, TimeUnit.MINUTES);

        //构建结果响应数据
        ValidateCodeVo codeVo = new ValidateCodeVo();
        codeVo.setCodeKey(codekey);
        codeVo.setCodeValue("data:image/png;base64," + imageBase64);
        return codeVo;
    }
}
